package com.zidongxiangxi.sharding.job.core.node;

import com.alibaba.fastjson.JSON;
import com.zidongxiangxi.sharding.job.core.ShardingJobConfig;
import com.zidongxiangxi.sharding.job.core.storage.NodeStorage;

/**
 * 配置节点
 *
 * @author chenxudong
 * @date 2021/02/18
 */
public class ConfigNode extends AbstractNode {
    private static final String ROOT = "config";

    private final String configNodeFullPath;

    public ConfigNode(final String jobName, final NodeStorage storage) {
        super(jobName, storage);
        this.configNodeFullPath = getFullPath(ROOT);
    }

    public boolean isConfigPath(final String path) {
        return configNodeFullPath.equals(path);
    }

    public ShardingJobConfig load(final boolean fromCache) {
        String result;
        if (fromCache) {
            result = storage.getJobNodeData(ConfigNode.ROOT);
            if (null == result) {
                result = storage.getJobNodeDataDirectly(ConfigNode.ROOT);
            }
        } else {
            result = storage.getJobNodeDataDirectly(ConfigNode.ROOT);
        }
        return JSON.parseObject(result, ShardingJobConfig.class);
    }

    public ShardingJobConfig setupJobConfig(final ShardingJobConfig jobConfig) {
        if (!storage.isJobNodeExisted(ConfigNode.ROOT) || jobConfig.isOverwrite()) {
            storage.replaceJobNode(ConfigNode.ROOT, JSON.toJSONString(jobConfig));
            return jobConfig;
        }
        return load(false);
    }
}
